package com.ikun.kunpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.*;
import com.ikun.kunpicturebackend.exception.BusinessException;
import com.ikun.kunpicturebackend.exception.ErrorCode;
import com.ikun.kunpicturebackend.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlPictureUpload extends PictureUploadTemplate{
    @Override
    protected void validPicture(Object inputSource) {
        String fileUrl = (String) inputSource;
        //非空
        ThrowUtils.throwIf(StrUtil.isBlank(fileUrl), ErrorCode.PARAMS_ERROR, "文件地址不能为空");

        // 1.校验URL格式：通过new URL
        try {
            new URL(fileUrl);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件地址格式不正确");
        }

        // 2.校验URL协议(http/https)
        ThrowUtils.throwIf(!(fileUrl.startsWith("http://") || fileUrl.startsWith("https://")), ErrorCode.PARAMS_ERROR,
                "仅支持HTTP或HTTPS协议的文件路径");

        // 3.发送Head请求，校验图片是否存在
        try (HttpResponse response = HttpUtil.createRequest(Method.HEAD, fileUrl).execute()) {
            // 3.1 创建head请求并执行
            // 3.2 判断是否正常返回
            int status = response.getStatus();
            // 未正常返回直接结束
            if (status != HttpStatus.HTTP_OK) {
                return;
            }

            // 4.校验文件类型
            //获取响应头信息
            String contentType = response.header(Header.CONTENT_TYPE);
            if (StrUtil.isNotBlank(contentType)) {
                // 允许的图片类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(contentType.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");
            }

            // 5.校验文件大小
            String contentLengthStr = response.header(Header.CONTENT_LENGTH);
            if (StrUtil.isNotBlank(contentLengthStr)) {
                long contentLength = Long.parseLong(contentLengthStr);
                // 2MB
                final long MAX_MEMORY = 2 * 1024 * 1024L;
                ThrowUtils.throwIf(contentLength > MAX_MEMORY, ErrorCode.PARAMS_ERROR, "文件大小不能超过2M");
            }
        } catch (NumberFormatException exception) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
        }
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        String fileUrl = (String) inputSource;
        // 获取原始文件名
        String fileName = FileUtil.getName(fileUrl);

        return fileName + ".webp";
    }

    @Override
    protected void processFile(Object inputSource, File file) throws IOException {
        String fileUrl = (String) inputSource;
        HttpUtil.downloadFile(fileUrl, file);
    }
}
